<template>
  <a-breadcrumb>
    <a-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="index">
      <span
        v-if="
          item.redirect === 'noRedirect' ||
          item.redirect === '' ||
          index === breadcrumbList.length - 1
        "
        class="gi_line_1"
      >
        {{ generateTitle(item.meta.title) }}
      </span>

      <span v-else @click="handleLink(item)" class="gi_line_1 item">
        {{ generateTitle(item.meta.title) }}
      </span>
    </a-breadcrumb-item>
  </a-breadcrumb>
</template>

<script setup lang="ts">
import { ref, watchEffect } from 'vue'
import type { RouteLocationMatched } from 'vue-router'
import { useRoute, useRouter } from 'vue-router'
import { generateTitle } from '@/utils/i18n'

const route = useRoute()
const router = useRouter()

const breadcrumbList = ref<RouteLocationMatched[]>([])

const getBreadcrumb = () => {
  // 只显示有标题的
  const matched = route.matched.filter((item) => item.meta && item.meta.title)
  const first = matched[0]
  if (!isHome(first)) {
    matched.unshift({
      path: '/',
      meta: { title: 'dashboard' },
    } as RouteLocationMatched)
  }
  breadcrumbList.value = matched.filter(
    (item) => item.meta && item.meta.title && item.meta.breadcrumb !== false,
  )
}

getBreadcrumb()

watchEffect(() => {
  if (route.path.startsWith('/redirect/')) return
  getBreadcrumb()
})

// 判断是否为首页
function isHome(route: RouteLocationMatched) {
  const name = (route?.name as string) || ''
  if (!name) return false
  return name.trim() === 'Home'
}

// 路由跳转
const handleLink = (item: RouteLocationMatched) => {
  const { redirect, path } = item
  if (redirect) {
    return router.push(redirect as string)
  }
  router.push(path)
}
</script>

<style scoped lang="scss">
.item {
  transition: all 0.3s;
  cursor: pointer;

  &.hover {
    color: $color-theme;
    font-weight: 600;
  }
}
</style>
